package com.zdpx.pxframework.auth.service.impl;

import com.zdpx.pxframework.auth.service.TokenService;
import com.zdpx.pxframework.core.constant.RedisKeyConstant;
import com.zdpx.pxframework.core.pojo.LoginUser;
import com.zdpx.pxframework.core.util.JwtUtil;
import com.zdpx.pxframework.redis.service.RedisService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import java.util.concurrent.TimeUnit;

import static com.zdpx.pxframework.core.constant.RedisKeyConstant.USER_TOKEN;

/**
 * Token 业务逻辑实现类
 *
 * @Description:
 * @Author: Cheng XiaoXiao
 * @Date: 2022/5/31 16:48
 */
@Service
public class TokenServiceImpl implements TokenService {

    @Resource
    private RedisService redisService;


    /**
     * 获取token在redis中的键
     *
     * @param token token
     * @return redis key
     */
    private String getTokenKey(String token) {
        return USER_TOKEN + token;
    }


    /**
     * 根据token获取用户信息
     *
     * @param token token
     * @return 用户信息
     */
    @Override
    public LoginUser getLoginUserByToken(String token) {
        LoginUser user = null;
        try {
            if (StringUtils.isNotEmpty(token)) {
                String userKey = JwtUtil.getUserKey(token);
                user = redisService.getCacheObject(getTokenKey(userKey));
                return user;
            }
        } catch (Exception e) {
        }
        return user;
    }

    /**
     * 删除用户token
     *
     * @param token 用户token
     */
    @Override
    public void deleteToken(String token) {
        if (StringUtils.isNotEmpty(token)) {
            String userTokenKey = getTokenKey(token);
            redisService.deleteObject(userTokenKey);
        }
    }

    /**
     * 刷新token的过期时间
     *
     * @param loginUser 登录用户
     */
    @Override
    public void refreshToken(LoginUser loginUser) {
        loginUser.setLoginTime(System.currentTimeMillis());
        loginUser.setExpireTime(loginUser.getLoginTime() + RedisKeyConstant.EXPIRATION * 60 * 1000);
        String userKey = getTokenKey(loginUser.getToken());
        redisService.setCacheObject(userKey, loginUser, RedisKeyConstant.EXPIRATION, TimeUnit.MINUTES);
    }

    /**
     * 刷新token的过期时间
     * @param token token
     */
    @Override
    public void refreshToken(String token) {
        refreshToken(getLoginUserByToken(token));
    }
}
